import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import http from '@/utils/http';
import { useUserStore } from './user';

export const useDocumentStore = defineStore('document', () => {
  const userStore = useUserStore();
  
  const documents = ref([]);
  const currentDocument = ref(null);
  const collaborators = ref([]);
  const documentVersions = ref([]);
  const currentDocumentVersion = ref(null);
  const loading = ref(false);
  const error = ref(null);
  const totalDocuments = ref(0);
  const totalDocumentVersions = ref(0);

  // 获取文档列表
  const fetchDocuments = async (page = 1, size = 10) => {
    try {
      loading.value = true;
      error.value = null;
      
      // 验证参数
      if (!page || page < 1 || !size || size < 1) {
        console.error('Invalid parameters for fetchDocuments:', { page, size });
        error.value = '参数无效';
        return;
      }
      
      // 确保用户已登录且完全初始化
      if (!userStore.token || !userStore.currentUser || !userStore.currentUser.id) {
        console.error('User not fully initialized in fetchDocuments');
        error.value = '用户未完全初始化';
        return;
      }
      
      const response = await http.post('/document/list/page/vo', {
        current: page,
        pageSize: size
      });
      
      documents.value = response.data.records;
      totalDocuments.value = response.data.total;
    } catch (err) {
      console.error('Failed to fetch documents:', err);
      error.value = '获取文档列表失败';
    } finally {
      loading.value = false;
    }
  };

  // 获取文档详情
  const fetchDocumentById = async (id) => {
    try {
      loading.value = true;
      error.value = null;
      
      // 验证文档ID
      if (!id) {
        console.error('Invalid document ID:', id);
        error.value = '文档ID不合法';
        return null;
      }
      
      // 确保用户已登录且完全初始化
      if (!userStore.token || !userStore.currentUser || !userStore.currentUser.id) {
        console.error('User not fully initialized in fetchDocumentById');
        error.value = '用户未完全初始化';
        return null;
      }
      
      const response = await http.get(`/document/get/vo?id=${id}`);
      
      currentDocument.value = response.data;
      return response.data;
    } catch (err) {
      console.error(`Failed to fetch document ${id}:`, err);
      error.value = '获取文档详情失败';
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 创建新文档
  const createDocument = async (title, content = '', templateId = null) => {
    try {
      loading.value = true;
      error.value = null;
      
      const payload = {
        title,
        content,
        status: 1 // 假设1表示正常状态
      };
      
      // 移除templateId参数，因为后端不支持
      // if (templateId) {
      //   payload.templateId = templateId;
      // }
      
      // 获取当前登录用户ID
      if (userStore.currentUser && userStore.currentUser.id) {
        payload.userId = userStore.currentUser.id;
      }
      
      const response = await http.post('/document/add', payload);
      
      // 刷新文档列表
      await fetchDocuments();
      
      return response.data;
    } catch (err) {
      console.error('Failed to create document:', err);
      error.value = '创建文档失败';
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 更新文档
  const updateDocument = async (id, updates) => {
    try {
      loading.value = true;
      error.value = null;
      
      const response = await http.post(`/document/edit`, {
        id,
        ...updates
      });
      
      // 如果当前正在查看的文档被更新，则更新当前文档
      if (currentDocument.value && currentDocument.value.id === id) {
        currentDocument.value = { ...currentDocument.value, ...updates };
      }
      
      // 更新文档列表中的文档
      const index = documents.value.findIndex(doc => doc.id === id);
      if (index !== -1) {
        documents.value[index] = { ...documents.value[index], ...updates };
      }
      
      return true;
    } catch (err) {
      console.error(`Failed to update document ${id}:`, err);
      error.value = '更新文档失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 删除文档
  const deleteDocument = async (id) => {
    try {
      loading.value = true;
      error.value = null;
      
      await http.post(`/document/delete`, { id });
      
      // 从列表中移除被删除的文档
      documents.value = documents.value.filter(doc => doc.id !== id);
      
      // 如果当前正在查看的文档被删除，则清空当前文档
      if (currentDocument.value && currentDocument.value.id === id) {
        currentDocument.value = null;
      }
      
      return true;
    } catch (err) {
      console.error(`Failed to delete document ${id}:`, err);
      error.value = '删除文档失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 获取文档协作者列表
  const fetchCollaborators = async (documentId) => {
    try {
      loading.value = true;
      error.value = null;
      
      const response = await http.post(`/documentUser/list`, {
        documentId
      });
      
      collaborators.value = response.data;
    } catch (err) {
      console.error(`Failed to fetch collaborators for document ${documentId}:`, err);
      error.value = '获取协作者列表失败';
    } finally {
      loading.value = false;
    }
  };

  // 添加协作者
  const addCollaborator = async (documentId, userId, permission) => {
    try {
      loading.value = true;
      error.value = null;
      
      // 确保userId作为字符串传递，避免大数值精度丢失
      await http.post('/documentUser/add', {
        documentId,
        userId: userId.toString(), // 确保userId是字符串
        permission // 'viewer', 'editor', 'admin'
      });
      
      // 刷新协作者列表
      await fetchCollaborators(documentId);
      
      return true;
    } catch (err) {
      console.error(`Failed to add collaborator to document ${documentId}:`, err);
      error.value = '添加协作者失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 更新协作者权限
  const updateCollaboratorPermission = async (id, permission) => {
    try {
      loading.value = true;
      error.value = null;
      
      await http.post('/documentUser/edit', {
        id,
        permission
      });
      
      // 更新协作者列表中的权限
      const index = collaborators.value.findIndex(c => c.id === id);
      if (index !== -1) {
        collaborators.value[index].permission = permission;
      }
      
      return true;
    } catch (err) {
      console.error(`Failed to update collaborator permission:`, err);
      error.value = '更新协作者权限失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 移除协作者
  const removeCollaborator = async (id, documentId) => {
    try {
      loading.value = true;
      error.value = null;
      
      await http.post('/documentUser/delete', { id });
      
      // 从列表中移除被删除的协作者
      collaborators.value = collaborators.value.filter(c => c.id !== id);
      
      return true;
    } catch (err) {
      console.error(`Failed to remove collaborator:`, err);
      error.value = '移除协作者失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 获取文档版本历史列表
  const fetchDocumentVersions = async (documentId, page = 1, size = 10) => {
    try {
      loading.value = true;
      error.value = null;
      
      // 验证参数
      if (!documentId || !page || page < 1 || !size || size < 1) {
        console.error('Invalid parameters for fetchDocumentVersions:', { documentId, page, size });
        error.value = '参数无效';
        return;
      }
      
      const response = await http.post('/documentVersion/list/page/vo', {
        documentId,
        current: page,
        pageSize: size
      });
      
      documentVersions.value = response.data.records;
      totalDocumentVersions.value = response.data.total;
    } catch (err) {
      console.error('Failed to fetch document versions:', err);
      error.value = '获取文档版本历史失败';
    } finally {
      loading.value = false;
    }
  };

  // 获取文档版本详情
  const fetchDocumentVersionById = async (id) => {
    try {
      loading.value = true;
      error.value = null;
      
      // 验证文档版本ID
      if (!id) {
        console.error('Invalid document version ID:', id);
        error.value = '文档版本ID不合法';
        return null;
      }
      
      const response = await http.get(`/documentVersion/get/vo?id=${id}`);
      
      currentDocumentVersion.value = response.data;
      return response.data;
    } catch (err) {
      console.error(`Failed to fetch document version ${id}:`, err);
      error.value = '获取文档版本详情失败';
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 删除文档版本
  const deleteDocumentVersion = async (id) => {
    try {
      loading.value = true;
      error.value = null;
      
      await http.post(`/documentVersion/delete`, { id });
      
      // 从列表中移除被删除的文档版本
      documentVersions.value = documentVersions.value.filter(version => version.id !== id);
      
      // 如果当前正在查看的文档版本被删除，则清空当前文档版本
      if (currentDocumentVersion.value && currentDocumentVersion.value.id === id) {
        currentDocumentVersion.value = null;
      }
      
      return true;
    } catch (err) {
      console.error(`Failed to delete document version ${id}:`, err);
      error.value = '删除文档版本失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 回溯到指定文档版本
  const backtrackDocumentVersion = async (id, documentId) => {
    try {
      loading.value = true;
      error.value = null;
      
      // 验证参数
      if (!id || !documentId) {
        console.error('Invalid parameters for backtrackDocumentVersion:', { id, documentId });
        error.value = '参数无效';
        return false;
      }
      
      // 调用回溯API
      await http.post(`/documentVersion/backtrack`, { id, documentId });
      
      // 刷新当前文档
      await fetchDocumentById(documentId);
      
      return true;
    } catch (err) {
      console.error(`Failed to backtrack to document version ${id}:`, err);
      error.value = '回溯文档版本失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  return {
    documents,
    currentDocument,
    collaborators,
    documentVersions,
    currentDocumentVersion,
    loading,
    error,
    totalDocuments,
    totalDocumentVersions,
    fetchDocuments,
    fetchDocumentById,
    createDocument,
    updateDocument,
    deleteDocument,
    fetchCollaborators,
    addCollaborator,
    updateCollaboratorPermission,
    removeCollaborator,
    fetchDocumentVersions,
    fetchDocumentVersionById,
    deleteDocumentVersion,
    backtrackDocumentVersion
  };

});